<template>
  <div class="equipmentCommunication">
    <div class="equipmentCommunication_treeBg">
      <MetaTreeList title-size="20" title="设备" :maxWidth="300" :icon="treeIcon" :default-props="defaultProps" :tree-data="equTreeData" @treeItemChoose="roloeItemChoose"></MetaTreeList>
    </div>
    <div class="equipmentCommunication_infoBg">
      <div v-if="Object.keys(roleInfoItem).length > 0" class="equipmentCommunication_info">
        <div class="equipmentCom_infoTitleBg">
          <div class="equipmentCom_infoTitle">设备信息</div>
          <div class="equipmentCom_infoContent">
            <div class="equipmentCom_infoItemBg">
              <img src="@/assets/images/v4/eInfo_showName.png" class="equipmentCom_infoItemIconShowName">
              <div class="equipmentCom_infoItemText">用户设备名称&nbsp;&nbsp;{{ roleInfoItem.customizeName && roleInfoItem.customizeName !== '' ? roleInfoItem.customizeName : roleInfoItem.equipmentname }}</div>
            </div>
            <div class="equipmentCom_infoItemBg">
              <img src="@/assets/images/v4/eInfo_showName.png" class="equipmentCom_infoItemIconName">
              <div class="equipmentCom_infoItemText">设备名称&nbsp;&nbsp;{{ roleInfoItem.alias }}</div>
            </div>
            <div class="equipmentCom_infoItemBg">
              <img src="@/assets/images/v4/eInfo_snid.png" class="equipmentCom_infoItemIconSnid">
              <div class="equipmentCom_infoItemText">设备版本&nbsp;&nbsp;v{{ roleInfoItem.version }} ({{ roleInfoItem.snid }})</div>
            </div>
            <div class="equipmentCom_infoItemBg">
              <!-- 1在线2调试3维修4报警 -->
              <img src="@/assets/images/v4/eInfo_equipmentStatus.png" class="equipmentCom_infoItemIconSnid">
              <div v-if="equipmentOnType == '2'" class="equipmentCom_infoItemText">设备状态&nbsp;&nbsp;调试</div>
              <div v-else-if="equipmentOnType == '3'" class="equipmentCom_infoItemText">设备状态&nbsp;&nbsp;维修</div>
              <div v-else-if="equipmentOnType == '4'" class="equipmentCom_infoItemText">设备状态&nbsp;&nbsp;报警</div>
              <div v-else class="equipmentCom_infoItemText">设备状态&nbsp;&nbsp;在线</div>
            </div>
          </div>
        </div>
        <div class="equipmentCom_optionArea">
          <div class="equipmentCom_optionTitle">设备通讯</div>
          <div class="equipmentCom_optionBg">
            <el-form :rules="rules" ref="equipmentComForm" :model="equCommunication" label-width="100px" class="equipmentComOption_form">
              <el-form-item label="通讯指令" prop="order" class="equipmentComOption_formItem">
                <el-row>
                  <el-col :span="16">
                    <el-input v-model="equCommunication.order"></el-input>
                  </el-col>
                  <el-col :span="8">
                    <el-button type="primary" @click="orderSend()" style="margin-left: 12px">发送</el-button>
                    <el-button type="primary" @click="getJournalList()" style="margin-left: 12px" plain>刷新日志</el-button>
                  </el-col>
                </el-row>
              </el-form-item>
              <el-form-item label="传输日志">
                <div class="equipmentComOption_journal">
                  <div v-for="(item,index) in journalList" :key="item.date + '_' + index" class="equipmentComOption_journalItem">
                    <div class="equipmentComOptionJournalItem_date">{{item.date}}</div>
                    <div class="equipmentComOptionJournalItem_source">{{item.source}}</div>
                    <div class="equipmentComOptionJournalItem_type">{{item.type}}</div>
                    <div class="equipmentComOptionJournalItem_message">{{item.message}}</div>
                  </div>
                </div>
              </el-form-item>
            </el-form>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import MetaTreeList from '../components/MetaTreeList'
import MetaNumberInput from '../components/MetaNumberInput'
import deepClone from '../utils/deepClone'
import utils from '../utils/utils'
export default {
  name: 'equipmentCommunication',
  components: {
    MetaTreeList,
    MetaNumberInput
  },
  data () {
    let checkOrder = (rule, value, callback) => {
      if (value.trim() === '') {
        return callback(new Error('请输入通讯指令'))
      }else{
        return callback()
      }
    }
    return {
      roleInfoItem: {},
      treeIcon: require("@/assets/images/v4/equipmentTreeIcon.png"),
      username: '',
      defaultProps: {
        children: 'list',
        label: 'name'
      },
      equTreeData: [],
      equipmentOnType: '', //1在线2调试3维修4报警
      equCommunication: {
        order: ''
      },
      rules: {
        order: [
          { required: true, validator: checkOrder, trigger: 'blur' },
        ],
      },
      journalList:  []
    }
  },
  created() {},
  mounted() {
    this.initEquipmentData()
  },
  destroyed() {},
  methods: {
    initEquipmentData() {
      this.$fetch({
        url: process.env.PROGOO_GATE_WATER + "admin/equipment/userarea",
        method: "post",
        data: {}
      }).then(res => {
        if (res.data.code === 200) {
          this.equTreeData = res.data.result
          let currentDataItem = {}
          for(let i in this.equTreeData) {
            this.equTreeData[i].name = "(" + this.equTreeData[i].area_jc + ")" + this.equTreeData[i].area_name
            this.equTreeData[i].level = 1
            for(let j in this.equTreeData[i].list) {
              if(this.equTreeData[i].list[j].customizeName && this.equTreeData[i].list[j].customizeName !== '') {
                this.equTreeData[i].list[j].name = this.equTreeData[i].list[j].customizeName
              }else {
                this.equTreeData[i].list[j].name = this.equTreeData[i].list[j].equipmentname
              }
              this.equTreeData[i].list[j].level = 2
              for(let key in this.equTreeData[i].list[j].equipmentRecord) {
                //子表中的这些参数不正确，不加入主表。
                if(key === 'aid' || key === 'id' || key === 'eid' || key === 'snid' || key === 'equipment_type') {
                  continue
                }
                this.equTreeData[i].list[j][key] = this.equTreeData[i].list[j].equipmentRecord[key]
              }
              if(Object.keys(this.roleInfoItem).length > 0 && this.roleInfoItem.id === this.equTreeData[i].list[j].id){
                currentDataItem = this.equTreeData[i].list[j]
              }
            }
          }
          if(Object.keys(currentDataItem).length > 0) {
            this.roleInfoItem = deepClone(currentDataItem)

            this.getEqtInfo((status,result) => {
              if(status) {
                this.equipmentOnType  = result.onType
              }
            })

          }else {
            this.roleInfoItem = {}
          }
          // this.$nextTick(() => {
          //   this.$refs.equipmentCommunication_list.setChoiceRole(this.roleInfoItem)
          // })


        }else {
          this.$notify.error({
            title: '错误',
            message: res.data.message
          });
        }
      })
    },
    roloeItemChoose(item) {
      if(item.level === 1) {
        return
      }
      this.roleInfoItem = {}
      this.$nextTick(() => {
        this.roleInfoItem = deepClone(item)
        this.getJournalList()
      })
    },
    getEqtInfo(callback) {
      this.$fetch({
        url: process.env.PROGOO_GATE_WATER + "admin/equipment/getEqtInfo?snid=" + this.roleInfoItem.snid,
        method: "post",
        data: {}
      }).then(res => {
        if (res.data.code === 200) {
          if(res.data.result.code && res.data.result.code == 400) {
            this.$notify.error({
              title: '错误',
              message: res.data.result.message
            });
            callback(false)
          }else {
            if(callback && typeof(callback) === 'function') {
              callback(true, res.data.result)
            }
          }
        }else {
          this.$notify.error({
            title: '错误',
            message: res.data.message
          });
        }
      })
    },
    checkEquipmentStatus() {
      // 检查设备通讯状态
      this.$fetch({
        url: process.env.PROGOO_GATE_WATER + "admin/equipment/infoBySid",
        method: "post",
        data: {
          snid: this.roleInfoItem.snid
        }
      }).then(res => {
        if(res.data.code == 200) {
          if(res.data.result.code && res.data.result.code == 400) {
            this.$notify.error({
              title: '通讯失败',
              message: ""
            });
            return
          }
          this.$message({
            message: '通讯成功',
            type: 'success'
          });
        }else {
          this.$notify.error({
            title: '错误',
            message: res.data.message
          });
        }
      })
    },
    orderSend() {
      this.$refs["equipmentComForm"].validate((valid) => {
        if (valid) {
          let orderTrim = this.equCommunication.order.trim()
          let order = orderTrim.replace(/[ ]/g,"")
          this.$fetch({
            url: process.env.PROGOO_COMMUNICATION + "admin/equipment/custom",
            method: "post",
            data: {
              "snid": this.roleInfoItem.snid,
              "msg": order
            }
          }).then(res => {
            console.log(res);
            if (res.data.result === true) {
              this.$message({
                message: '发送成功',
                type: 'success'
              });
              this.getJournalList()
            }else {
              this.$notify.error({
                title: '错误',
                message: res.data.message
              });
            }
          })
        } else {
          console.log('error submit!!');
          return false;
        }
      });

    },
    getJournalList() {
      this.journalList = []
      this.$fetch({
        url: process.env.PROGOO_COMMUNICATION + "admin/equipment/refreshMessage",
        method: "post",
        data: {
          "snid": this.roleInfoItem.snid,
        }
      }).then(res => {
        if (res.data.code === 200) {
          this.journalList = res.data.result
        }else {
          this.$notify.error({
            title: '错误',
            message: res.data.message
          });
        }
      })
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang="less">
.equipmentCommunication{
  background-color: #EAECF0;
  width: 100%;
  height: 100%;
  display: flex;
  flex-grow: 1;
  box-sizing: border-box;
  padding: 8px 0 8px 12px;
  // overflow-y: scroll;
  .equipmentCommunication_treeBg {
    height: 100%;
    background-color: white;
    border-radius: 6px;
    margin-right: 12px;
  }
  .equipmentCommunication_infoBg {
    height: 100%;
    box-sizing: border-box;
    flex: 1;
    padding-right: 12px;
    overflow-x: scroll;
    .equipmentCommunication_info {
      width: 100%;
      height: 100%;
      border: 1px solid rgb(228, 234, 236);
      flex: 1;
      min-width: 1360px;
      box-sizing: border-box;
      // background-color: white;
      // padding: 15px;
      .equipmentCom_infoTitleBg {
        height: 80px;
        width: 100%;
        float: left;
        border-radius: 6px;
        // margin-top: 20px;
        padding-bottom: 10px;
        background-color: white;
        padding: 0 28px 10px;
        box-sizing: border-box;
        .equipmentCom_infoTitle {
          font-size: 18px;
          float: left;
          height: 45px;
          line-height: 45px;
          width: 100%;
        }
        .equipmentCom_infoContent {
          width: 100%;
          float: left;
          .equipmentCom_infoItemBg {
            height: 20px;
            float: left;
            padding-left: 75px;
            display: flex;
            align-items: center;
            margin-bottom: 5px;
            .equipmentCom_infoItemIconShowName {
              width: 16px;
              height: 16px;
            }
            .equipmentCom_infoItemIconName {
              width: 16px;
              height: 16px;
            }
            .equipmentCom_infoItemIconSnid {
              width: 16px;
              height: 16px;
            }
            .equipmentCom_infoItemText {
              font-size: 16px;
              color: #999;
              margin-left: 8px;
            }
          }
        }
        .equipmentCom_delBtn {
          float: right;
        }
      }
      .equipmentCom_optionArea {
        height: calc(100% - 90px);
        width: 100%;
        float: left;
        padding: 10px 28px 30px 0;
        background-color: white;
        margin-top: 10px;
        border-radius: 6px;
        box-sizing: border-box;
        .equipmentCom_optionTitle {
          font-size: 18px;
          float: left;
          height: 45px;
          line-height: 45px;
          width: 100%;
          box-sizing: border-box;
          padding-left: 28px;
        }
        .equipmentCom_optionBg {
          width: 100%;
          display: flex;
          box-sizing: border-box;
          padding: 0 28px;
          .equipmentComOption_form {
            width: 100%;
            .equipmentComOption_formItem {
              width: 60%;
            }
            .equipmentComOption_journal {
              width: 100%;
              height: 500px;
              border: 1px solid #DCDFE6;
              border-radius: 5px;
              overflow-y: scroll;
              .equipmentComOption_journalItem {
                width: 100%;
                float: left;
                box-sizing: border-box;
                padding: 12px 16px 0;
                font-size: 13px;
                .equipmentComOptionJournalItem_date {
                  width: 15%;
                  float: left;
                }
                .equipmentComOptionJournalItem_source {
                  width: 5%;
                  float: left;
                }
                .equipmentComOptionJournalItem_type {
                  width: 10%;
                  float: left;
                }
                .equipmentComOptionJournalItem_message {
                  width: 70%;
                  float: left;
                  word-break: break-all;
                  line-height: 20px;
                }
              }
            }
          }
        }
      }
    }
  }
  .dialogFooter {
    display: flex;
    justify-content: center;
    margin-top: 0.5rem;
  }
}
</style>
